<?php

namespace App\Http\Controllers;

use App\Jobs\cmqJob;
use Illuminate\Support\Facades\DB;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Freyo\LaravelQueueCMQ\Queue\Driver\Account;
use Freyo\LaravelQueueCMQ\Queue\Driver\Message;
use Freyo\LaravelQueueCMQ\Queue\Driver\QueueMeta;

class testController extends BaseController
{
    /**
     * Redis 测试
     * @param Request $request
     * @return $this|\Illuminate\Http\JsonResponse|mixed|string
     * Date : 2017-07-03
     * Time : 10:37
     * User : Yaowenzhu
     */
    public function redis(Request $request)
    {
        // 获取参数
        $phone = $request->input('phone');
        if(empty($phone)){
            return response()->json(['code'=>'6333','msg'=>'参数错误']);
        }
        // 查询缓存
        $res = app('redis')->get($phone);

        if(empty($res)){
            // 查询数据库
            /*$res = DB::select(
                'select make,model,year,created_at,updated_at,phone from cars
                 where phone = :phone', ['phone' => $phone]
            );*/
            $res = DB::table('cars')->select('make','model','year','created_at','updated_at','phone')
                   ->where('phone',$phone)->first();
            if($res){
                // 存入缓存系统
                $json_res = json_encode($res);
                app('redis')->set($phone,$json_res);
                return response()->json(['code'=>'0000','msg'=>'请求成功','data'=>$res]);
            }else{
                return response()->json(['code'=>'0033','msg'=>'暂无数据']);
            }
        }else{
            $res = json_decode($res,true);
            return response()->json(['code'=>'0000','msg'=>'请求成功','data'=>$res]);
        }
    }

    /**
     * Memcached 测试
     * @param Request $request
     * @return $this|\Illuminate\Http\JsonResponse|mixed|string
     * Date : 2017-07-03
     * Time : 10:38
     * User : Yaowenzhu
     */
    public function memcached(Request $request)
    {
        // 获取参数
        $phone = $request->input('phone');
        if(empty($phone)){
            return response()->json(['code'=>'6333','msg'=>'参数错误']);
        }
        // 删除缓存
        //$res = app('memcache')->delete($phone);
        // 从缓存中获取数据
        $res = app('memcache')->get($phone);

        if(empty($res)){
            // 查询数据库
            /*$res = DB::select(
                'select make,model,year,created_at,updated_at,phone from cars
                 where phone = :phone', ['phone' => $phone]
            );*/
            $res = DB::table('cars')->select('make','model','year','created_at','updated_at','phone')
                   ->where('phone',$phone)->first();

            if(!empty($res)){
                // 存入缓存系统
                $json_res = json_encode($res);
                app('memcache')->set($phone,$json_res);
                return response()->json(['code'=>'0000','msg'=>'成功','data'=>$res]);
            } else {
                return response()->json(['code'=>'0033','msg'=>'暂无数据']);
            }
        }else{
            $res = json_decode($res,true);
            return response()->json(['code'=>'0000','msg'=>'成功','data'=>$res]);
        }
    }

    /**
     * cmq 测试
     * @param Request $request
     * @return $this|\Illuminate\Http\JsonResponse|mixed|string
     * Date : 2017-07-03
     * Time : 10:38
     * User : Yaowenzhu
     */
    public function cmq(Request $request)
    {
        // 获取参数
        $phone = $request->input('phone');
        if(empty($phone)){
            return response()->json(['code'=>'6333','msg'=>'参数错误']);
        }

//        #### lumen自带queue ####
//        $job = new cmqJob($phone);
//        dispatch($job->onQueue('orderMQ'));
//        dispatch($job->allOnQueue('orderMQ'));
//        #### lumen自带queue ####

        $queue_name = env('CMQ_QUEUE');
        $my_account = new Account(env('CMQ_QUEUE_HOST'), env('CMQ_SECRET_ID'), env('CMQ_SECRET_KEY'));

        $my_queue = $my_account->get_queue($queue_name);

        $queue_meta = new QueueMeta();
        $queue_meta->queueName = $queue_name;
        $queue_meta->pollingWaitSeconds = 10;       // 消息接受长轮询等待时间
        $queue_meta->visibilityTimeout = 10;        // 取出消息隐藏时长
        $queue_meta->maxMsgSize = 1024;             // 消息最大长度
        $queue_meta->msgRetentionSeconds = 3600;    // 消息生命周期

        try {
//            // 创建队列
//            $my_queue->create($queue_meta);
//            // 设置队列属性
//            $my_queue->set_attributes($queue_meta);
//            // 获取队列列表
//            $result = $my_account->list_queue();
//            // 获取队列属性
//            $queue_meta = $my_queue->get_attributes();
            // 向队列发送消息
            $msg_body = "I am test message.";
            $msg      = new Message($msg_body);
            $re_msg   = $my_queue->send_message($msg);
            // 消费消息
            $recv_msg = $my_queue->receive_message(3);
            var_dump('消息添加成功msgId=>' . $re_msg->msgId, $recv_msg);
//            // 批量发送消息
//            $messages = array();
//            for ($i=0; $i<3; $i++) {
//                $msg_body = "I am test message " . $i;
//                $msg      = new Message($msg_body);
//                $messages[] = $msg;
//            }
//            $re_msg_list = $my_queue->batch_send_message($messages);
//            // 批量消费消息
//            $wait_seconds  = 3;
//            $num_of_msg    = 3;
//            $recv_msg_list = $my_queue->batch_receive_message($num_of_msg, $wait_seconds);
//            foreach ($recv_msg_list as $key=>$val){
//                // 删除消息
//                $my_queue->delete_message($val->receiptHandle);
//            }
//            // 删除消息
//            $my_queue->delete_message($recv_msg_list->receiptHandle);
            // 删除队列
//            $my_queue->delete();

        } catch (CMQExceptionBase $e) {
            return "Create Queue Fail! Exception: " . $e;
        }
    }
}
